package com.markerhub.Shiro;

import cn.hutool.core.bean.BeanUtil;
import com.markerhub.Util.JwtUtils;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/*AccountProFile
    若token存在，会进入这里
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取token
        JwtToken jwtToken=(JwtToken)token;

        String userId= jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        User user =userService.getById(Long.valueOf(userId));

        if(user==null){
            throw new UnknownAccountException("账号不存在");
        }

        if(user.getStatus() == -1){
            throw new LockedAccountException("账户已被锁定");
        }

        //返回一些公开数据
        AccountProfile profile=new AccountProfile(); //封装返回对象
        //这里是将user中同名的属性复制倒profile
        BeanUtil.copyProperties(user,profile);
        //返回可公开数据，token密钥，以及realm的名称
        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
